#! /bin/sh

#Goto here
here="/users/left/guillaume/bots"
cd $here

#Test if the number of input arguments is correct
ARGS=5;
E_BADARGS=99;
if [ $# -ne "$ARGS" ]
then
  echo "Usage: `basename $0` city [LBintensity] [UBintensity] [LBdirection] [UBdirection]"
  exit $E_BADARGS
fi

#City
city=$1

#Lintensity, Uintensity (0 < x < 100 m/s), Ldirection, Udirection (0 < y < 360 degs)
Lint=$2; Uint=$3; Ldir=$4; Udir=$5
LBint=0; UBint=100; LBdir=0; UBdir=360

#Checks consistency of input data: LBx <= Lx < Ux <= UBx
if (( "$Lint" >= "$Uint" || "$LBint" > "$Lint" || "$UBint" < "$Uint" || \
"$Ldir" >= "$Udir" || "$LBdir" > "$Ldir" || "$UBdir" < "$Udir"))
then 
  echo "Error: $2 $3 $4 $5 are inconsistent"
  exit $E_BADARGS
fi

#temporary file and log file
file="wind${city}"

#Wind twitter bot
twitbot=login:passw

#Timestamp the log file
echo ------------------------------------------------------->> $file.log
date >> $file.log

#Extract messages
#cat `find .. | grep -i _${city} | sort | tail -n 1` > $file.txt
cat `find .. | grep -i _${city} | sort | tail -n 1` | \
awk -v Uint=$Uint -v Lint=$Lint -v Udir=$Udir -v Ldir=$Ldir \
'{ if (Lint<$2 && $2<Uint && Ldir<$3 && $3<Udir) print "D" $1 "  " $2 "  " $3}' > $file.txt

cat $file.txt | while read mess; 
do

#Twit the message variable away
curl -u ${twitbot//./} -d status="${mess}" http://twitter.com/statuses/update.xml >> $file.log
#echo ${twitbot//./} $mess
sleep 1s

done
